package com.xdr.core.controller;

import java.util.Date;
import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.xdr.core.model.User;
import com.xdr.core.service.UserService;

@Controller
@RequestMapping(value = "/users")
public class UserController {
	@Autowired
	private UserService userService;

	/**
	 * Returns the user with the given id
	 * 
	 * @param id
	 * @return the user as a JSON object
	 */
	@RequestMapping(method = RequestMethod.GET, headers = { "Content-Type=application/json" })
	public @ResponseBody
	List<User> doGet() {
		List<User> users = userService.findAll();
		return users;
	}

	/**
	 * Returns the user with the given id
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.GET, headers = { "content-type=application/json" })
	public @ResponseBody
	User doGet(@PathVariable long id) {
		User user = userService.find(id);
		User u1 = new User(new Date(1), "a@a", true, true, new Date(3),
				new Date(5), 10, "12321321", "LOL", new Date(123), "user",
				null, null, null, null);
		user.setCompanies(null);
		user.setCreatedBy(null);
		user.setModifiedBy(null);
		user.setRoles(null);
		return user;
	}

	/**
	 * Saves the user from the JSON object in the RequestBody
	 */
	@RequestMapping(method = RequestMethod.POST, headers = { "content-type=application/json" })
	@ResponseStatus(HttpStatus.CREATED)
	public @ResponseBody
	void doPost(@RequestBody @Valid User user) {
		userService.save(user);
	}

	/**
	 * Updates the entity with the given id with the values of the JSON object
	 * in the RequestBody
	 * 
	 * @param id
	 * @param entity
	 */
	@ResponseStatus(HttpStatus.NO_CONTENT)
	@RequestMapping(value = "/{id}", method = RequestMethod.PUT, headers = { "content-type=application/json" })
	public void doPut(@PathVariable long id, @RequestBody @Valid User user) {
		userService.update(user);
	}

	/**
	 * Deletes the user with the given id
	 * 
	 * @param id
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, headers = { "content-type=application/json" })
	@ResponseStatus(HttpStatus.NO_CONTENT)
	public void doDelete(@PathVariable long id) {
		userService.deleteById(id);
	}
}
